<template>
  <div class="article-details">
    <!-- 导航栏 -->
    <van-nav-bar class="login-headers" title="黑马头条">
      <van-icon slot="left" name="arrow-left" @click="$router.back()" />
    </van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div v-if="loading" class="loading-wrap">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div v-else-if="article.title" class="article-detail">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ article.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="article.aut_photo"
          />
          <div slot="title" class="user-name">{{ article.aut_name }}</div>
          <div slot="label" class="publish-date">
            {{ article.pubdate | relativeTime }}
          </div>
          <!-- 关注用户 -->
          <!-- <follow-user
            class="follow-btn"
            :aut-id="article.aut_id"

            :is-followed="article.is_followed"
            @is-followed="article.is_followed = $event"
            上边这两句代码简写为
            v-model="article.is_followed"

            使用简写形式在组件上使用v-model
            接收值的默认名称是value
            方法的默认名称是input

            修改默认名称需要在子组件修改

            一个组件只能使用一次v-model
            多次可以使用属性.sync修饰符
          
          /> -->
          <follow-user
            class="follow-btn"
            :aut-id="article.aut_id"
            v-model="article.is_followed"
          />
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div
          class="article-content markdown-body"
          v-html="article.content"
          ref="article-content"
        ></div>
        <van-divider>正文结束</van-divider>
        <!-- 评论组件 -->
        <comm-list
          :artId="article.art_id"
          :list="commentList"
          @search-data="commentNumber = $event.total_count"
          @reply-item="onReply"
        />
        <!-- 底部区域 -->
        <div class="article-bottom">
          <van-button
            class="comment-btn"
            type="default"
            round
            size="small"
            @click="isshow = true"
            >写评论</van-button
          >
          <van-icon name="comment-o" :info="commentNumber" color="#777" />
          <!-- 收藏组件 -->
          <collection-articles
            v-model="article.is_collected"
            :art-id="article.art_id"
          />
          <!-- 点赞组件 -->
          <like-articles v-model="article.attitude" :art-id="article.art_id" />
          <van-icon name="share" color="#777777"></van-icon>
        </div>
        <!-- 发布评论组件 -->
        <van-popup v-model="isshow" position="bottom">
          <collection-post
            :target="article.art_id"
            @post-comment="onPostcomment"
            @reply-item="onReply"
          />
        </van-popup>
        <!-- /底部区域 -->
      </div>

      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div v-else-if="errState" class="error-wrap">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div v-else class="error-wrap">
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="obtainArticle"
          >点击重试</van-button
        >
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>

    <!-- 评论回复模块 -->
    <van-popup v-model="isReplyShow" position="bottom" style="height: 100%;">
      <comm-reply
        v-if="isReplyShow"
        :comment="commentReply"
        @close="isReplyShow = false"
      />
    </van-popup>
  </div>
</template>

<script>
// 导入获取文章详情接口
import { getArticleDetails } from "@/api/article";
// 引入图片预览
import { ImagePreview } from "vant";
// 导入关注用户的组件
import followUser from "@/components/follow-user";
// 导入收藏文章组件
import collectionArticles from "@/components/collection-articles";
// 导入点赞接口组件
import likeArticles from "@/components/like-articles";
// 导入文章评论组件
import commList from "./components/comments-list.vue";
// 导入发布评论组件
import collectionPost from "./components/comments-post.vue";
// 导入评论回复组件
import commReply from "./components/comments-reply.vue";

export default {
  // 组件名称
  name: "articleDetails",
  // 组件参数 接收来自父组件的数据
  props: {
    articleId: {
      type: [Number, String],
      required: true,
    },
  },
  // 局部注册的组件
  components: {
    followUser,
    collectionArticles,
    likeArticles,
    commList,
    collectionPost,
    commReply,
  },
  // 给所有后代组件提供数据
  provide: function() {
    return {
      articleId: this.articleId,
    };
  },

  // 组件状态值
  data() {
    return {
      article: {}, //存储获取到的文章数据
      loading: true, //显示加载中状态
      errState: 0, //错误状态码
      commentNumber: 0, //评论默认数量
      isshow: false, //控制弹出层是否显示
      commentList: [], // 评论列表
      isReplyShow: false, //评论回复弹出层
      commentReply: {}, //当前点击评论项
    };
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  // 组件方法
  methods: {
    async obtainArticle() {
      this.loading = true;
      try {
        const { data } = await getArticleDetails(this.articleId);

        setTimeout(() => {
          this.imgPreview();
        }, 0);
        this.article = data.data;
      } catch (error) {
        if (error.response && error.response.status == 404) {
          this.errState = 404;
        }
      }
      // 无论成功或失败都要关闭加载中状态
      this.loading = false;
    },

    // 图片预览
    imgPreview() {
      const articleContent = this.$refs["article-content"];
      // 获取所有img图片
      const imgs = articleContent.querySelectorAll("img");
      // 用来存放img的路径
      const images = [];
      // 遍历所有img图片
      imgs.forEach((item, i) => {
        // 将图片的路径存放在数组中
        images.push(item.src);
        // 给每个图片设置一个点击事件
        item.onclick = () => {
          // 点击图片触发图片预览
          ImagePreview({
            // 图片的路径
            images,
            // 图片的起始位置,从0开始
            startPosition: 1,
          });
        };
      });
    },

    // 发布评论弹出层
    onPostcomment(data) {
      // 关闭弹出层
      this.isshow = false;
      // 将发布内容显示到列表顶部
      this.commentList.unshift(data.new_obj);
    },

    // 点击回复弹出层
    onReply(comment) {
      this.isReplyShow = true;
      this.commentReply = comment;
      // console.log(comment);
    },
  },
  // 以下是生命周期钩子   注：没用到的钩子请自行删除
  /**
   * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
   */
  created() {
    this.obtainArticle();
  },
  /**
   * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
   * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
   */
  mounted() {},
};
</script>

<style scoped lang="less">
@import "./github-markdown.css";

.article-details {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>
